#define _CRT_SECURE_NO_WARNINGS 1

class Solution {
public:
    int latestTimeCatchTheBus(vector<int>& buses, vector<int>& passengers, int capacity) {
        sort(buses.begin(), buses.end());
        sort(passengers.begin(), passengers.end());
        int np = passengers.size(), nb = buses.size();
        int pbus = 0, ppas = 0;
        int rem_pbus = 0, rem_ppas = 0;
        int space = 0;
        while (pbus < nb)
        {
            int k = capacity;
            while (ppas < np && passengers[ppas] <= buses[pbus] && k-- > 0)
            {
                ppas++;
            }
            pbus++;
            if (pbus == nb)
            {
                space = k;
            }
        }
        --pbus;
        --ppas;
        if (ppas < 0) ppas = 0;
        if (buses[pbus] != passengers[ppas] && space > 0) return buses[pbus];
        else
        {
            while (ppas > 0 && passengers[ppas] == passengers[ppas - 1] + 1) ppas--;
            return passengers[ppas] - 1;
        }
        return 0;
    }
};